from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.utils.decorators import method_decorator
from myapp.myser import *
#导入类视图
from django.views import View

from myapp.models import *
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

from PIL import Image,ImageDraw

 # 导包
import redis

  # 定义IP地址和端口
host = '127.0.0.1'
port = 6379
  # 链接对象
r = redis.Redis(host=host,port=port)

# 上传文件
class UploadFile2(View):
    def post(self,request):
        # 接收文件
        myfile = request.FILES.get('file')
        # 建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT,'',str(myfile.name).replace('"','')),'wb')
        # 进行写文件
        for chunk in myfile.chunks():
            f.write(chunk)
        # 关闭文件流
        f.close()
        # 返回文件名
        return HttpResponse(json.dumps({'filename':myfile.name},ensure_ascii=False),
                            content_type='application/json')

 # 七牛云密钥接口
from qiniu import Auth

class QiNiu2(APIView):
    def get(self,request):
        # 声明密钥对象
        q = Auth('Xhm0gJwxb7tppghoHulMB-pb7tuRKg8b7zAe4cEf','HCTVbbhpMaDR9Ef0gWWp3LDH4QfbWwig3CnaTEy0')
        # 生成令牌
        token = q.upload_token('lianghaochen')

        return Response({'uptoken':token})

# 定义装饰器
def my_decorator(func):
    def wrapper(request,*args,**kwargs):

        # 判断jwt逻辑
        uid = request.GET.get('uid')
        cline_jwt = request.GET.get('jwt',None)

        decode_jwt = jwt.decode(cline_jwt,'123', algorithms=['HS256'])
        if decode_jwt['uid'] != str(uid):
            return HttpResponse('您篡改了用户id')
        return func(request,*args,**kwargs)
    return wrapper

# 用户信息类
class UserInfo2(APIView):
    # 导入装饰器
    @method_decorator(my_decorator)
    def get(self, request):
        uid = request.GET.get("uid")

        # 查询数据
        user = User.objects.get(id=int(uid))

        # 序列化对象
        user_ser = Userser(user)

        return Response(user_ser.data)